let chatChe = JSON.parse(localStorage.getItem('chatChe')) || {};
let startIndex = 0
let initchatChe = {};
export function initCache () {
  startIndex = 0
  initchatChe = JSON.parse(localStorage.getItem('chatChe')) || {}
  console.log("🚀 ~ file: index.js:5 ~ initCache ~ initchatChe:", initchatChe)
}
export function setLocalStorage (id, msgItem) {
console.log("🚀 ~ file: index.js:10 ~ setLocalStorage ~ id:", id)

  if (!chatChe[id]) {//没有id就创建
    chatChe[id] = []
  }
  chatChe[id] = chatChe[id].concat({ msg: msgItem.msg, isReceived: msgItem.isReceived, timestamp: msgItem.timestamp })
  console.log("🚀 ~ file: index.js:16 ~ setLocalStorage ~ chatChe[id]:", chatChe[id])
  //超过2MB就删除最旧的100条数据
  if (JSON.stringify(chatChe).length > 2 * 1024 * 1024) {
    deleteOldestEntries(chatChe, 100)
  }
  console.log("🚀 ~ file: index.js:13 ~ setLocalStorage ~ JSON.stringify(chatChe).length > 5:", JSON.stringify(chatChe).length)
  localStorage.setItem('chatChe', JSON.stringify(chatChe))
}

export function getLocalStorage (id) {
  console.log("🚀 ~ file: index.js:24 ~ getLocalStorage ~ id:", id)
  let result = []
  if (!initchatChe[id]) {
    return [];
  }

  let endIndex = initchatChe[id].length;
  if (endIndex <= startIndex && endIndex < 20) {// 如果没有超过20条数据，则直接返回
    result = initchatChe[id].slice(startIndex, endIndex);
  } else if (endIndex <= startIndex) { // 如果超过总长度就返回空数组
    result = [];
  } else if (endIndex - startIndex < 20) { // 如果超过20条数据，但没有超过20条数据，则返回剩余数据
    result = initchatChe[id].slice(0, endIndex - startIndex);
    startIndex += 20;
  } else {// 超过20条数据，则返回20条数据
    result = initchatChe[id].slice(endIndex - 20 - startIndex, endIndex - startIndex);
    startIndex += 20;
  }

  showTime([...result])
  console.log("result:", result, startIndex);
  return result;
}

/**
 * @description: 依次遍历删除指定条数的数据
 * @param {*} data 删除的数据源
 * @param {*} iterations 删除的条数
 * @return {*}
 * @author: lihk
 */function deleteOldestEntries (data, iterations) {
  for (let i = 0; i < iterations; i++) {
    let oldestTimestamp = Infinity;
    let oldestKey = '';

    // 遍历数据对象的每个键
    for (let key in data) {
      const array = data[key];
      if (array.length > 0) {
        // 找到每个键对应数组中最老的时间戳
        if (array[0].timestamp < oldestTimestamp) {
          oldestTimestamp = array[0].timestamp;
          oldestKey = key;
        }
      }
    }

    // 删除最老的元素
    if (oldestKey) {
      data[oldestKey].shift();
    }
  }
}
/**
 * @description: 根据时间进行设置显示的时间和日期
 * @param {*}
 * @return {*}
 * @author: lihk
 */
export function showTime (messages) {
  console.log("🚀 ~ file: index.js:76 ~ showTime ~ messages:", messages)
  messages.forEach((message, index) => {
    const timestamp = new Date(message.timestamp);
    let showTime = false;

    // 判断是否是今天
    const isToday = new Date().toDateString() === timestamp.toDateString();

    // 判断是否需要显示时间和日期
    if (index === 0) {
      showTime = true;
    } else {
      const prevTimestamp = new Date(messages[index - 1].timestamp);
      const timeDiff = (timestamp - prevTimestamp) / (1000 * 60); // 计算相邻消息的时间间隔（分钟）
      if (timeDiff >= 5) {
        showTime = true;
      }
    }

    // 根据条件显示时间和日期
    if (isToday) {
      message.time = showTime ? timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '';
    } else {
      message.date = showTime ? timestamp.toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' }) : '';
      message.time = showTime ? timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '';
    }
  });
}


/**
 * @description: 判断是不是显示现在的时间
 * @param {*} timestamp 上一个时间戳
 * @param {*} nowStamp 现在的时间戳
 * @return {*} 返回现在的时间
 * @author: lihk
 */
export function isShowTime (timestamp, nowStamp) {
  const currentTime = new Date();
  const timestampDate = new Date(timestamp);
  const isDifferentDate = currentTime.toDateString() !== timestampDate.toDateString();
  const isOverFiveMinutes = Math.abs(currentTime.getTime() - timestampDate.getTime()) >= (5 * 60 * 1000);

  // 返回对象结构更清晰
  const time = isDifferentDate || isOverFiveMinutes ? new Date(nowStamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''
  if (time === 'Invalid Date') {
    time = '';
  }

  return time;
}